package cn.innosmart.aq.view.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.tutk.IOTC.P2PTunnelAPIs;
import com.tutk.P2PCam264.MainActivity;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.innosmart.aq.BuildConfig;
import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.BoxListAdapter;
import cn.innosmart.aq.adapter.BoxListMenuItemAdapter;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.bean.BannerInfo;
import cn.innosmart.aq.bean.BoxBean;
import cn.innosmart.aq.bean.LvMenuItem;
import cn.innosmart.aq.customize.AddBoxPopupWindow;
import cn.innosmart.aq.isp.ISPTool;
import cn.innosmart.aq.util.NetworkTool;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.util.UpdateManager;
import cn.innosmart.aq.view.activity.base.BaseActivity;
import cn.innosmart.aq.view.activity.pay.PayDemoActivity;
import cn.innosmart.aq.view.activity.pay.VIPPayActivity;
import cn.innosmart.qrcode.view.CaptureActivity;

/**
 * Created by David on 2015/7/7.
 */
public class BoxListActivity extends BaseActivity implements ViewPagerEx.OnPageChangeListener, BaseSliderView.OnSliderClickListener {
    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;
    private final int REQUESTCODE_IPUTADDBOX = 1;
    private final int REQUESTCODE_LANSEARCHADDBOX = 6;
    private final int REQUESTCODE_MODIFYBOX = 2;
    private final int REQUESTCODE_DELETEBOX = 3;
    private final int REQUESTCODE_LOGIN = 4;
    private final int REQUESTCODE_QRCODE = 5;
    private final int RESULTCODE_SUCCESS = 0;
    private final int RESULTCODE_BACKPRESSED = -1;
    private final int HeaderClicked = 1;
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    //添加Box的Popupwindow
    private AddBoxPopupWindow addBoxPopupWindow;
    /**
     * 添加Box的items点击事件
     */
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            addBoxPopupWindow.dismiss();
            switch (v.getId()) {
                //二维码扫描
                case R.id.btn_qrcode:
                    Intent qrcodeIntent = new Intent(BoxListActivity.this, CaptureActivity.class);
                    startActivityForResult(qrcodeIntent, REQUESTCODE_QRCODE);
                    break;
                //局域网扫描
                case R.id.btn_lan_search:
                    if (NetworkTool.getInstance().isWifiConnected(BoxListActivity.this)) {
                        Intent lanSearchIntent = new Intent(BoxListActivity.this, BoxModifyActivity.class);
                        lanSearchIntent.putExtra("flag", REQUESTCODE_LANSEARCHADDBOX);
                        startActivityForResult(lanSearchIntent, REQUESTCODE_LANSEARCHADDBOX);
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    } else {
                        NetworkTool.getInstance().setNetworkMethod(BoxListActivity.this);
                    }
                    break;
                //手动输入
                case R.id.btn_input:
                    Intent inputIntent = new Intent(BoxListActivity.this, BoxModifyActivity.class);
                    inputIntent.putExtra("flag", REQUESTCODE_IPUTADDBOX);
                    startActivityForResult(inputIntent, REQUESTCODE_IPUTADDBOX);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
                case R.id.btn_cancel:
                    break;
            }
        }
    };
    //设置Drawer
    private DrawerLayout mDrawer;
    private ListView left_menu;
    private RelativeLayout rl_header;
    private List<LvMenuItem> mItems;
    private BoxListMenuItemAdapter menuItemAdapter;
    //检查APP更新
    private UpdateManager updateManager;
    private ArrayList<BoxBean> boxBeanList = SystemConstant.boxBeanList;
    private ListView lv_boxlist;
    private BoxListAdapter mBoxListAdapter;
    private TextView navUsername;
    private ImageView navHeadIcon;
    private RelativeLayout rl_app_setting;
    private SliderLayout sliderLayout;
    //   String imageUrl,String title,String linkUrl, String filePath
    private ArrayList<BannerInfo> bannerInfoList = new ArrayList<>();
    private View.OnClickListener mOnTextOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.edit_text:
                    //编辑
//                    if (SystemConstant.loginStatus == SystemConstant.Offline) {
//                        showToast(getString(R.string.operate_befor_login));
//                        break;
//                    }
                    BoxBean editBean = (BoxBean) v.getTag();
                    Intent intent = new Intent(BoxListActivity.this, BoxModifyActivity.class);
                    intent.putExtra("flag", REQUESTCODE_MODIFYBOX);
                    intent.putExtra("BoxBean", editBean);
                    int position = -1;
                    for (int i = 0; i < boxBeanList.size(); i++) {
                        if (editBean.getUid().equals(boxBeanList.get(i).getUid())) {
                            position = i;
                        }
                    }
                    intent.putExtra("position", position);
                    startActivityForResult(intent, REQUESTCODE_MODIFYBOX);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
                case R.id.rl_boxlayout:
                case R.id.connect_text:
                    //连接
                    BoxBean connectBean = (BoxBean) v.getTag();

                    SystemConstant.currentBoxBean = connectBean;

                    //判断网络状态再进行连接
                    if (NetworkTool.getInstance().isOpenNetwork(BoxListActivity.this)) {
                        Intent intent1 = new Intent(BoxListActivity.this, BoxDetailActivity.class);
                        intent1.putExtra("BoxBean", connectBean);
                        startActivity(intent1);
                        finish();
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    } else {
                        if (NetworkTool.getInstance().isWifiConnected(BoxListActivity.this)) {
                            Intent intent2 = new Intent(BoxListActivity.this, BoxDetailActivity.class);
                            intent2.putExtra("BoxBean", connectBean);
                            startActivity(intent2);
                            finish();
                            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        } else {
                            showToast(getString(R.string.network_error));
                        }
                    }
                    break;
                case R.id.rl_addlayout:
                    //添加Box
//                    if (SystemConstant.loginStatus == SystemConstant.Offline) {
//                        showToast(getString(R.string.operate_befor_login));
//                        return;
//                    }
                    //添加gateway的方式actionsheet
                    initMyPopupWindow();
                    break;
            }
        }
    };
    /**
     * 左划菜单点击事件监听
     */
    private View.OnClickListener OnLeftMenuOnClickedLitener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            System.out.println("position=" + position);
            switch (position) {
                case 0:
                    mHandler.sendEmptyMessage(HeaderClicked);
                    break;
                case 1:
                    //跳转到资源
                    Intent resourceIntent = new Intent();
                    resourceIntent.setAction("android.intent.action.VIEW");
                    Uri resource_url = Uri.parse("http://www.gangganghao.com.cn/support/detail/?id=100");
                    resourceIntent.setData(resource_url);
                    startActivity(resourceIntent);
                    break;
                case 2:
                    Intent payIntent = new Intent(BoxListActivity.this, PayDemoActivity.class);
                    startActivity(payIntent);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
                case 3:
                    //退出
                    exit();
                    break;
            }
        }
    };
    private boolean isModify = false;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            String msg = "";
            switch (menuItem.getItemId()) {
//                case R.id.action_edit:
//                    //编辑状态
//                    isModify = !isModify;
//                    mBoxListAdapter.startModify(isModify);
//                    break;
                case R.id.action_message:
                    //原来的IM 入口 现已隐藏
//                    if (NetworkTool.getInstance().isOpenNetwork(getApplicationContext())) {
//                        Intent intent = new Intent(BoxListActivity.this, FriendActivity.class);
//                        startActivity(intent);
//                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//                    } else {
//                        showToast(getString(R.string.network_error));
//                    }
                    break;
            }
            if (!msg.equals("")) {
                Toast.makeText(BoxListActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    };
    private Menu menu;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    String str = (String) msg.obj;
                    showToast(str);
                    break;
                case HeaderClicked:
                    //头像的点击
                    mDrawer.closeDrawers();
                    leftMenuHeaderClicked();
                    break;
            }
        }
    };

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boxlist);
        setBar();
        //设置左滑菜单
        setDrawer();
        setUpDrawer();
//        checkUpdate(); //由于上架不可用自动更新
        initView();
        //告知dispatcher server清除再次报警标志,
        changeIsp();

//        if(SystemConstant.loginStatus != SystemConstant.Online) {
//            openCountLoginActivity();
//        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
    }

    private int points;
    private TextView tvPoints;

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitleTextAppearance(getApplicationContext(), R.style.ToolbarTitleAppearance);
//        toolbar.setNavigationIcon(null);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_menu);

        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences gatwayInfoSp = getSharedPreferences(SystemConstant.Project, MODE_PRIVATE);
                JSONObject loginSp = SharedUtil.getInstance().readLoginInfo();
                String username = null;
                String password = null;
                try {
                    username = loginSp.getString("username");
                    password = loginSp.getString("password");

                    String url = "http://api.innosmart.cn:1337/account/find?where={\"username\":\"" + username + "\"}";
                    System.out.println(url);
                    JsonArrayRequest jsonStatementUrl = new JsonArrayRequest(url,
                            new Response.Listener<JSONArray>() {
                                @Override
                                public void onResponse(JSONArray response) {
                                    try {
                                        tvPoints.setText("" + response.getJSONObject(0).getInt("AQB"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    Log.d("TAG", response.toString());
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.e("TAG", error.getMessage(), error);
                                }
                            });


                    AQApplication.getInstance().mQueue.add(jsonStatementUrl);


                } catch (JSONException e) {
                    e.printStackTrace();
                }


                mDrawer.openDrawer(GravityCompat.START);
            }
        });
        findViewById(R.id.tv_headtitle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SystemConstant.loginStatus == SystemConstant.Offline) {
                    openCountLoginActivity();
                } else {
                    mDrawer.openDrawer(GravityCompat.START);
                }
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitleClickListener();
        initToolBarAnimate();
    }

    private void initMyPopupWindow() {
        addBoxPopupWindow = new AddBoxPopupWindow(BoxListActivity.this, itemsOnClick);
        addBoxPopupWindow.showAtLocation(BoxListActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void setDrawer() {
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        left_menu = (ListView) findViewById(R.id.left_menu);
    }

    /**
     * 设置菜单
     */
    private void setUpDrawer() {
        LayoutInflater inflater = LayoutInflater.from(this);
//        AutoUtils.autoSize(left_menu);
        View headView = inflater.inflate(R.layout.header_just_username, left_menu, false);
        AutoUtils.autoSize(headView);
        left_menu.addHeaderView(headView);
        rl_header = (RelativeLayout) left_menu.findViewById(R.id.rl_header);
        mItems = new ArrayList<LvMenuItem>(
                Arrays.asList(
                        new LvMenuItem(R.drawable.setting_icon, getString(R.string.activity_count_setting)),
                        new LvMenuItem(R.drawable.online_manual, getString(R.string.online_manual)),
                        new LvMenuItem(R.drawable.market_icon, getString(R.string.fee)),
                        new LvMenuItem(R.drawable.exit_icon, getString(R.string.boxdetail_leftmenu_exit))
                ));
        menuItemAdapter = new BoxListMenuItemAdapter(this, mItems);
        left_menu.setAdapter(menuItemAdapter);
        menuItemAdapter.setOnClickListener(OnLeftMenuOnClickedLitener);
        rl_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(HeaderClicked);
            }
        });
    }

    //设置Toolbar文字点击监听
    private void setTitleClickListener() {
        try {
            Field titleField = Toolbar.class.getDeclaredField("mTitleTextView");
            titleField.setAccessible(true);
            TextView barTitleView = barTitleView = (TextView) titleField.get(toolbar);
            barTitleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (SystemConstant.loginStatus == 0) {
                        openCountLoginActivity();
                    } else {
                        mDrawer.openDrawer(GravityCompat.START);
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开登陆界面
     */
    private void openCountLoginActivity() {
        Intent intent = new Intent(BoxListActivity.this, CountActivity.class);
        intent.putExtra("flag", REQUESTCODE_LOGIN);
        startActivityForResult(intent, REQUESTCODE_LOGIN);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 遍历toolbar所有子View并赋予他们动画效果
     */
    private void initToolBarAnimate() {
        int noOfChild = toolbar.getChildCount();
        View view;
        toolbar.setAlpha(0);
        toolbar.setTranslationY(-450);
        toolbar.animate().setDuration(1000).translationY(0).alpha(1);
        /* 循环遍历toolbar的子节点，并赋予动画效果 */
        for (int i = 0; i < noOfChild; i++) {
            view = toolbar.getChildAt(i);
            view.setTranslationY(-450);
            view.animate().setStartDelay(500).setDuration(800).translationY(0);
        }
    }

    private void checkUpdate() {
        updateManager = new UpdateManager(BoxListActivity.this);
        updateManager.geUpdateInfo(1);
    }

    /**
     * 获取Banner信息
     *
     * @param context
     */
    private void getNewBannerInfo(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("AQProject", Context.MODE_PRIVATE);
        String bannerinfo = sharedPreferences.getString("bannerInfo", null);
        JSONArray bannerArray = null;
        if (bannerinfo == null) {
            //此处表示第一次打开APP时就没连上网
            bannerinfo = BuildConfig.BANNERINFO;
        }
        try {
            bannerArray = new JSONArray(bannerinfo);
            int lenth = bannerArray.length();
            BannerInfo bannerInfo;
            for (int i = 0; i < lenth; i++) {
                JSONObject jsonObject = new JSONObject(bannerArray.get(i).toString());
                bannerInfo = new BannerInfo(jsonObject.toString());
                bannerInfoList.add(bannerInfo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //初始化控件
    private void initView() {
        tvPoints = (TextView) findViewById(R.id.tv_points);
        lv_boxlist = (ListView) findViewById(R.id.lv_boxlist);
        mBoxListAdapter = new BoxListAdapter(BoxListActivity.this);
        mBoxListAdapter.setOnItemClickListener(mOnTextOnClickListener);
        lv_boxlist.setAdapter(mBoxListAdapter);
        getNewBannerInfo(this);
        sliderLayout = (SliderLayout) findViewById(R.id.sliderlayout);
        for (BannerInfo bannerInfo : bannerInfoList) {
            TextSliderView textSliderView = new TextSliderView(this);
            // initialize a SliderLayout
            textSliderView.description(bannerInfo.getTitle())
                    .empty(R.drawable.banner_info)
                    .image(bannerInfo.getImageUrl())
                    .setScaleType(BaseSliderView.ScaleType.Fit)
                    .setOnSliderClickListener(this);
            //add your extra information
            textSliderView.bundle(new Bundle());
            textSliderView.getBundle().putString("extra", bannerInfo.getLinkUrl());
            sliderLayout.addSlider(textSliderView);
        }
        sliderLayout.setPresetTransformer(SliderLayout.Transformer.Accordion);
        sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
        sliderLayout.setCustomAnimation(new DescriptionAnimation());
        sliderLayout.setDuration(4000);
        sliderLayout.addOnPageChangeListener(this);
        navUsername = (TextView) findViewById(R.id.nav_username);
        navHeadIcon = (ImageView) findViewById(R.id.nav_headIcon);
        rl_app_setting = (RelativeLayout) findViewById(R.id.rl_app_setting);
        rl_app_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BoxListActivity.this, AppSettingActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });

        findViewById(R.id.newsView).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(BoxListActivity.this, NewsActivity.class);
                BoxListActivity.this.startActivity(myIntent);
            }
        });
        findViewById(R.id.shopView).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                jumpFishList();
//                Intent myIntent = new Intent(BoxListActivity.this, ShopActivity.class);
//                BoxListActivity.this.startActivity(myIntent);
            }
        });
        findViewById(R.id.nearbyView).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(BoxListActivity.this, NearbyActivity.class);
                BoxListActivity.this.startActivity(myIntent);
            }
        });
    }

    private void jumpFishList() {
        Intent intent = new Intent(BoxListActivity.this, FishListActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    //跳转到浏览器
    private void switchToBrowser(String linkUrl) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("http://bbs.innosmart.cn/forum.php?gid=54");
        intent.setData(content_url);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == REQUESTCODE_IPUTADDBOX) {
            BoxBean boxBean = data.getParcelableExtra("BoxBean");
            boxBeanList.add(boxBean);
            if (SystemConstant.loginStatus == SystemConstant.Offline) {
                SharedUtil.getInstance().writeLocalGatewayInfo(boxBeanList);
            }
        } else if (resultCode == REQUESTCODE_MODIFYBOX) {
            BoxBean boxBean = data.getParcelableExtra("BoxBean");
            int position = data.getIntExtra("position", -1);
            boxBeanList.remove(position);
            boxBeanList.add(position, boxBean);
            if (SystemConstant.loginStatus == SystemConstant.Offline) {
                SharedUtil.getInstance().writeLocalGatewayInfo(boxBeanList);
            }
        } else if (resultCode == REQUESTCODE_DELETEBOX) {
            int position = data.getIntExtra("position", -1);
//            BoxBean boxBean=data.getParcelableExtra("BoxBean");
            boxBeanList.remove(position);
            if (SystemConstant.loginStatus == SystemConstant.Offline) {
                SharedUtil.getInstance().writeLocalGatewayInfo(boxBeanList);
            }
        } else if (resultCode == REQUESTCODE_LOGIN) {

        } else if (requestCode == REQUESTCODE_QRCODE) {
            if (resultCode == RESULT_OK) {
                switchToAddActivityByQrcode(data);
            } else if (resultCode == RESULTCODE_BACKPRESSED) {
            }
        }
        mBoxListAdapter.notifyDataSetChanged();
    }

    /**
     * 通过二维码方式添加设备
     *
     * @param data
     */
    private void switchToAddActivityByQrcode(Intent data) {
        String result = data.getStringExtra("QRCODERESULT");
        Intent intent = new Intent(BoxListActivity.this, BoxModifyActivity.class);
        intent.putExtra("uid", result);
        intent.putExtra("flag", REQUESTCODE_IPUTADDBOX);
        startActivityForResult(intent, REQUESTCODE_IPUTADDBOX);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            setOverflowIconVisiable(menu);
        }
        return super.onMenuOpened(featureId, menu);
    }

    //不再需要
    public void setOverflowIconVisiable(Menu menu) {
        try {
            Class clazz = Class.forName("com.android.internal.view.menu.MenuBuilder");
            Field field = clazz.getDeclaredField("mOptionalIconsVisible");
            if (field != null) {
                field.setAccessible(true);
                field.set(menu, true);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        getMenuInflater().inflate(R.menu.menu_toolbar, menu);
        this.menu = menu;
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onResume() {
        System.out.println("BoxListActivity OnResume！");
        resumToolBar(SystemConstant.loginStatus);
        resumDrawer(SystemConstant.loginStatus);
        boxBeanList = SystemConstant.boxBeanList;
        resetModifyStatus();
        sliderLayout.startAutoCycle();

        SystemConstant.has_check_fw_version_in_current_fragment = 0;

        super.onResume();
    }

    /**
     * 清除报警标志
     */
    public void changeIsp() {
        ArrayList<String> uids = new ArrayList<>();
        if (SystemConstant.boxBeanList != null)
            for (BoxBean boxBean : SystemConstant.boxBeanList) {
                uids.add(boxBean.getUid());
            }
        ISPTool.getInstance().changeEvent(uids, 0);
    }

    //进入修改状态
    private void resetModifyStatus() {
        if (isModify) {
            isModify = !isModify;
            //菜单变为正常状态
//            menu.findItem(R.id.action_edit).setIcon(R.drawable.toolbar_edit);
        }
        mBoxListAdapter.startModify(false);
    }

    //重设菜单
    private void resumDrawer(int status) {
        if (status == 0) {
            navUsername.setText(getString(R.string.title_login));
            navHeadIcon.setImageResource(R.drawable.head_icon);
        } else {
            navUsername.setText(SystemConstant.nickname);
        }
    }

    //重设菜单栏
    private void resumToolBar(int status) {
        if (status == 0) {
            toolbar.setTitle("");
            ((TextView) findViewById(R.id.tv_headtitle)).setText(getString(R.string.title_login));
            toolbar.setNavigationIcon(null);
        } else {
            toolbar.setTitle("");
            ((TextView) findViewById(R.id.tv_headtitle)).setText(SystemConstant.nickname);
            toolbar.setNavigationIcon(null);
        }
    }

    @Override
    protected void onDestroy() {
        System.out.println("BoxListActivity onDestroy！");
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        // ATTENTION: This was auto-generated to implement the App Indexing API.

    }

    @Override
    protected void onStop() {
        System.out.println("BoxListActivity onStop！");
        sliderLayout.stopAutoCycle();
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawers();
            return;
        }
        exitBy2Click();
    }

    //    左滑菜单头像点击事件
    private void leftMenuHeaderClicked() {
        if (SystemConstant.loginStatus == SystemConstant.Online) {
            //在线跳出在线账户中设置界面
            Intent intent = new Intent(BoxListActivity.this, CountSettingActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        } else {
            //离线 弹出登录界面
            openCountLoginActivity();
        }
    }

    /**
     * 获取P2P版本号
     *
     * @return
     */
    private String verN2Str() {
        int ver = P2PTunnelAPIs.P2PTunnel_Version();
        String strVer = String.format("%d.%d.%d.%d",
                (ver >> 24) & 0xff, (ver >> 16) & 0xff, (ver >> 8) & 0xff, ver & 0xff);
        return strVer;
    }

    /**
     * 双击退出
     */
    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, R.string.activity_box_list_exit_by_two, Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
//            finish();
            System.exit(0);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onSliderClick(BaseSliderView slider) {
//        Toast.makeText(this, slider.getBundle().get("extra") + "", Toast.LENGTH_SHORT).show();
        switchToBrowser(slider.getBundle().get("extra") + "");
    }
}